package cn.cdeden.knowledge.controller.schedule;

import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.EnterpriseFolderTree;
import cn.cdeden.knowledge.domain.SysCalendarPersonnel;
import cn.cdeden.knowledge.domain.SysResource;
import cn.cdeden.knowledge.domain.SysResourceFollow;
import cn.cdeden.knowledge.domain.dto.*;
import cn.cdeden.knowledge.domain.vo.UserDeptVO;
import cn.cdeden.knowledge.service.SysCalendarPersonnelService;
import cn.cdeden.knowledge.service.SysResourceFollowService;
import cn.cdeden.knowledge.service.SysResourceService;
import cn.cdeden.knowledge.utils.BeanCopyUtil;
import cn.cdeden.knowledge.utils.PageUtil;
import cn.cdeden.system.api.RemoteDeptService;
import cn.cdeden.system.api.RemoteUserService;
import cn.cdeden.system.api.domain.vo.RemoteDeptVo;
import cn.cdeden.system.api.domain.vo.RemoteUserVo;
import cn.cdeden.system.api.model.LoginUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.MapUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author guojunxu
* @date 2024-07-09
**/
@RestController
@RequiredArgsConstructor
//@Api(tags = "日历资源管理管理")
@RequestMapping("/api/sysResource")
public class SysResourceController {

    private final SysResourceService sysResourceService;

    private final SysResourceFollowService sysResourceFollowService;

    private final SysCalendarPersonnelService sysCalendarPersonnelService;

    @DubboReference
    private final RemoteUserService remoteUserService;
    @DubboReference
    private final RemoteDeptService remoteDeptService;

    @GetMapping
//    @Log("查询日历资源")
//    @ApiOperation("查询日历资源")
    public R<TableDataInfo<SysResourceDto>> query(SysResourceQueryParam query, Pageable pageable){
        TableDataInfo<SysResourceDto> info = sysResourceService.queryAll(query,pageable);
        return R.ok(info);
    }

    @PostMapping
//    @Log("新增日历资源")
//    @ApiOperation("新增日历资源")
    public R create(@Validated @RequestBody SysResourceDto resources){
        LoginUser loginUser = LoginHelper.getLoginUser();
        resources.setCreateBy(loginUser.getUserId());
        return R.ok(sysResourceService.insert(resources));
    }

    @PutMapping
//    @Log("修改日历资源")
//    @ApiOperation("修改日历资源")
    public R update(@Validated @RequestBody SysResourceDto resources){
        return R.ok(sysResourceService.updateById(resources));
    }

    @DeleteMapping
//    @Log("删除日历资源")
//    @ApiOperation("删除日历资源")
    @Transactional
    public R delete(@RequestBody Set<Long> ids) {
        sysResourceFollowService.remove(new QueryWrapper<SysResourceFollow>().in("resource_id", ids));
        return R.ok(sysResourceService.deleteByIds(ids));
    }

    @GetMapping("/get-resource-follow")
//    @Log("个人资源关注列表")
//    @ApiOperation("个人资源关注列表")
    public R<List<SysResource>> getResourceFollow(@RequestParam Map<String, Object> parameters) {
        String resourceName = MapUtils.getString(parameters, "resourceName");
        LoginUser loginUser = LoginHelper.getLoginUser();
        List<SysResourceFollow> sysResourceFollowList = sysResourceFollowService.list(new QueryWrapper<SysResourceFollow>().eq("user_id", loginUser.getUserId()));
        List<Long> resourceIds = sysResourceFollowList.stream().map(SysResourceFollow::getResourceId).collect(Collectors.toList());
        List<SysResource> sysResourceList = new ArrayList<>();
        if (!resourceIds.isEmpty()) {
            QueryWrapper<SysResource> sysResourceQueryWrapper = new QueryWrapper<>();
            sysResourceQueryWrapper.in("resource_id", resourceIds);
            if (resourceName != null) {
                sysResourceQueryWrapper.like("resource_name", "%" +resourceName + "%");
            }
            sysResourceList = sysResourceService.list(sysResourceQueryWrapper);
        }
        return R.ok(sysResourceList);
    }

    @PostMapping("/add-resource-follow")
//    @Log("新增个人关注资源列表")
//    @ApiOperation("新增个人关注资源列表")
    public R addResourceFollow(@RequestBody ResourceDTO resourceDTO) {
        SysResourceFollow sysResourceFollow = new SysResourceFollow();
        LoginUser loginUser = LoginHelper.getLoginUser();
        sysResourceFollow.setUserId(loginUser.getUserId());
        sysResourceFollow.setResourceId(resourceDTO.getResourceId());
        return R.ok(sysResourceFollowService.save(sysResourceFollow));
    }

    @DeleteMapping("/delete-resource-follow")
//    @Log("删除个人关注资源列表")
//    @ApiOperation("删除个人关注资源列表")
    public R deleteResourceFollow(@RequestParam Long resourceId) {
        QueryWrapper<SysResourceFollow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", LoginHelper.getUserId());
        queryWrapper.eq("resource_id", resourceId);
        return R.ok(sysResourceFollowService.remove(queryWrapper));
    }


    @PostMapping("/resource-follow-show")
//    @Log("查询关注资源的日程数据")
//    @ApiOperation("查询关注资源的日程数据")
    public R<List<SysCalendarDto>> resourceFollowShow(@RequestBody CalendarDTO calendarDTO) {
        return R.ok(sysResourceService.resourceFollowShow(calendarDTO.getResourceIds(), calendarDTO.getStartDate(), calendarDTO.getEndDate()));
    }

    @GetMapping("/get-by-dept")
//    @Log("根据部门ID获取日历中的人员")
//    @ApiOperation("根据部门ID获取日历中的人员")
    public R<TableDataInfo<UserDeptVO>> getByDept(@RequestParam Map<String,Object> parameters, @RequestParam("deptId") String deptId,
                                                @RequestParam("scheduleId") Long scheduleId, @RequestParam("nickName") String nickName, Pageable pageable) {
        List<Long> deptIdList = new ArrayList<>();
        if (deptId != null) {
            deptIdList = Arrays.stream(deptId.split(","))
                    .filter(s -> !s.trim().isEmpty())
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
        }
        List<Long> userIds = sysCalendarPersonnelService.list(new QueryWrapper<SysCalendarPersonnel>().eq("schedule_id", scheduleId)).stream().map(SysCalendarPersonnel::getRangeValue).collect(Collectors.toList());
        //日历的所有的参与的人员
        List<RemoteUserVo> userList = remoteUserService.selectListByIds(userIds);
//        List<Long> deptIds = userList.stream().map(RemoteUserVo::getDeptId).collect(Collectors.toList());
        Map<Long, RemoteDeptVo> deptMap = remoteDeptService.selectAll().stream().collect(Collectors.toMap(RemoteDeptVo::getDeptId, dept -> dept));
        List<UserDeptVO> userDeptVOList = new ArrayList<>();
        TableDataInfo<UserDeptVO> userDeptVOPage = new TableDataInfo<>();

        if (deptIdList.isEmpty()) {
            List<Long> userIdList = userList.stream().map(RemoteUserVo::getUserId).collect(Collectors.toList());
            TableDataInfo<RemoteUserVo> userPage = remoteUserService.getUserPage(userIdList, pageable.getPageSize(), pageable.getPageNumber());
            userPage.getRows().forEach(v -> {
                UserDeptVO userDeptVO = new UserDeptVO();
                BeanCopyUtil.copyProperties(v, userDeptVO);
                userDeptVO.setId(v.getUserId());
                userDeptVO.setDeptName(deptMap.get(v.getDeptId()).getDeptName());
                userDeptVOList.add(userDeptVO);
            });
            userDeptVOPage.setRows(userDeptVOList);
            userDeptVOPage.setPage(userPage.getPage());
            userDeptVOPage.setPageSize(userPage.getPageSize());
            userDeptVOPage.setTotal(userPage.getTotal());
            return R.ok(userDeptVOPage);
        }
        Set<Long> departmentAndSubDepartments = sysResourceService.getDepartmentAndSubDepartments(deptIdList);
        //通过部门查询出来的所有的人员
        List<RemoteUserVo> totalUser = remoteUserService.select(nickName,departmentAndSubDepartments);
        //筛选出当前部门中参与了日历的人员
        totalUser = totalUser.stream().filter(v -> userIds.contains(v.getUserId())).collect(Collectors.toList());
        List<Long> totalUserIdList = totalUser.stream().map(RemoteUserVo::getUserId).collect(Collectors.toList());
        if (totalUserIdList.isEmpty()) {
            return R.ok(new TableDataInfo<>());
        }
        TableDataInfo<RemoteUserVo> userPage = remoteUserService.getUserPage(totalUserIdList, pageable.getPageSize(), pageable.getPageNumber());
        userPage.getRows().forEach(v -> {
            UserDeptVO userDeptVO = new UserDeptVO();
            BeanCopyUtil.copyProperties(v, userDeptVO);
            userDeptVO.setDeptName(deptMap.get(v.getDeptId()).getDeptName());
            userDeptVOList.add(userDeptVO);
        });
        userDeptVOPage.setRows(userDeptVOList);
        userDeptVOPage.setPage(userPage.getPage());
        userDeptVOPage.setPageSize(userPage.getPageSize());
        userDeptVOPage.setTotal(userPage.getTotal());
        return R.ok(userDeptVOPage);
    }

    @GetMapping("/get-all-resource")
//    @Log("查询所有资源")
//    @ApiOperation("查询所有资源")
    public R<Map<String, Object>> getAllResource(@RequestParam Map<String, Object> params) {
        String resourceName = MapUtils.getString(params, "resourceName");
        LoginUser loginUser = LoginHelper.getLoginUser();
        QueryWrapper<SysResource> sysResourceQueryWrapper = new QueryWrapper<SysResource>();
        if (resourceName != null && resourceName != "") {
            sysResourceQueryWrapper.like("resource_name", "%" + resourceName + "%");
        }
        List<SysResource> sysResourceList = sysResourceService.list(sysResourceQueryWrapper);
        Map<String, Object> data = new HashMap<>();
        List<Long> resourceIds = sysResourceFollowService.list(new QueryWrapper<SysResourceFollow>().eq("user_id", loginUser.getUserId())).stream().map(SysResourceFollow::getResourceId).collect(Collectors.toList());
        data.put("resource", sysResourceList);
        data.put("resource_id", resourceIds);
        return R.ok(data);
    }

    /*
//    @Log("导出SysResourceController")
//    @ApiOperation("导出SysResourceController")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('sysResource:list')")
    public void download(HttpServletResponse response, SysResourceQueryParam query) throws IOException {
        sysResourceService.download(sysResourceService.queryAll(query), response);
    }*/

}
